package com.alipay.rebate.shop.configuration.shiro.realm;

import com.alipay.rebate.shop.configuration.shiro.token.WeixinToken;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.constants.UserContant;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.service.customer.CustomerUserService;
import com.alipay.rebate.shop.utils.EncryptUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeixinShiroRealm extends AuthorizingRealm {

	private final Logger logger = LoggerFactory.getLogger(WeixinShiroRealm.class);

	private CustomerUserService userService;

	public WeixinShiroRealm(CustomerUserService userService) {
		this.userService = userService;
		this.setCredentialsMatcher(new HashedCredentialsMatcher(Sha256Hash.ALGORITHM_NAME));
	}
	
	@Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof WeixinToken;
    }
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		logger.debug("Get into WeixinShiroRealm");
		WeixinToken weixinToken = (WeixinToken)token;
		logger.debug("WeixinToken is :{}",weixinToken);
		String userName = weixinToken.getUserName();
		logger.debug("userName is :{}",userName);
		String openId = weixinToken.getOpenId();
		logger.debug("openId is: {}",openId);
		UserDto user = userService.getUserInfoForWeixinLogin(openId);
		if(user == null){
			throw new BusinessException("openId 对应用户不存在",StatusCode.USER_NOT_EXISTS);
		}
		if(UserContant.USER_STATUS_BLACK.equals(user.getUserStatus())){
			throw new BusinessException(StatusCode.USER_IN_BLACK_LIST);
		}
		if(UserContant.USER_STATUS_LOGOFF.equals(user.getUserStatus())){
			throw new BusinessException("账号不存在",StatusCode.INTERNAL_ERROR);
		}
		// 验证
		user.setEncryptPwd(new Sha256Hash(openId, EncryptUtil.encryptSalt).toHex());
		return new SimpleAuthenticationInfo(user, user.getEncryptPwd(), ByteSource.Util.bytes(
				EncryptUtil.encryptSalt), "dbRealm");
	}


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return null;
	}

	
}
